import { useEffect, useState } from 'react'
import styles from './Pin.module.css'
import { useNavigate } from 'react-router-dom'
import axios from '../../axios'
import { Toast } from 'antd-mobile'

// 拼团商品类型
interface GroupProduct {
    id: string;
    title: string;
    image: string;
    currentPrice: number;
    originalPrice: number;
    sales?: number;
    stock?: number;
    description?: string;
    unit?: string;
    category?: string;
    tags?: string[];
    activity?: string[];
    status?: string;
}

export default function Pin() {
    const navigate = useNavigate()
    const [groupData, setGroupData] = useState<GroupProduct[]>([])
    const [loading, setLoading] = useState(false)

    // 获取拼团商品数据
    useEffect(() => {
        const fetchGroupProducts = async () => {
            try {
                setLoading(true)
                const response = await axios.get('http://localhost:3000/jjx/getgroupproducts')
                if (response.data.code === 200) {
                    console.log('拼团商品：', response.data.data)
                    // 过滤掉禁用状态的商品
                    const activeProducts = (response.data.data || []).filter((product: any) => 
                        product.status === 'active'
                    )
                    setGroupData(activeProducts)
                }
            } catch (error) {
                console.error('获取拼团商品失败:', error)
                Toast.show('获取拼团商品失败')
            } finally {
                setLoading(false)
            }
        }

        fetchGroupProducts()
    }, [])

    return (
        <div className={styles.pageWrap}>
            {/* 顶部导航栏 */}
            <div className={styles.navBar}>
                <span className={styles.back} onClick={()=>{
                    navigate('/app/home')
                }}>&lt;</span>
                <span className={styles.title}>今日拼团</span>
                <span className={styles.cartIcon} onClick={() => {
                    navigate('/app/cars')
                }}>🛒</span>
            </div>
            {/* 流程图 */}
            <div className={styles.banner}>
                <div className={styles.bannerImg}></div>
                <div className={styles.bannerSteps}>
                    <span>①发起拼团</span>
                    <span>——</span>
                    <span>②邀请参与</span>
                    <span>——</span>
                    <span>③人满发货</span>
                </div>
            </div>
            {/* 商品列表 */}
            <div className={styles.listWrap}>
                {loading ? (
                    <div className={styles.loading}>加载中...</div>
                ) : (
                    groupData.map(item => (
                    <div className={styles.card} key={item.id}>
                        <div className={styles.cardImgWrap}>
                            <img src={item.image} alt={item.title} style={{ width: '100%', height: '100%', objectFit: 'cover', borderRadius: '10px' }} />
                        </div>
                        <div className={styles.cardInfo}>
                            <div className={styles.cardTitleRow}>
                                <span className={styles.cardName}>{item.title}</span>
                                <span className={styles.cardSpec}>{item.unit || '件'}</span>
                            </div>
                            <div className={styles.cardTagRow}>
                                <span className={styles.cardGroupNum}><span className={styles.groupIcon}>👥</span>3人团</span>
                                <span className={styles.cardTotal}>已团:{item.sales || 0}份</span>
                            </div>
                            <div className={styles.cardPriceRow}>
                                <span className={styles.cardPrice}>￥{item.currentPrice}</span>
                                <span className={styles.cardOriginPrice}>￥{(item.originalPrice || 0).toFixed(2)}</span>
                                <button 
                                    className={styles.cardBtn}
                                    onClick={() => {
                                        // 添加到购物车
                                        const cartItem = {
                                            id: item.id,
                                            title: item.title,
                                            image: item.image,
                                            currentPrice: item.currentPrice,
                                            originalPrice: item.originalPrice,
                                            quantity: 1,
                                            category: item.category || '拼团商品',
                                            tags: item.tags || ['特惠拼团'],
                                            activity: item.activity || ['特惠拼团'],
                                            stock: item.stock || 100,
                                            selected: true
                                        };
                                        
                                        // 从 localStorage 获取现有购物车
                                        const existingCart = localStorage.getItem('cart');
                                        let cartItems = existingCart ? JSON.parse(existingCart) : [];
                                        
                                        // 检查商品是否已在购物车中
                                        const existingItemIndex = cartItems.findIndex((cartItem: any) => cartItem.id === item.id);
                                        
                                        if (existingItemIndex >= 0) {
                                            // 如果已存在，增加数量
                                            cartItems[existingItemIndex].quantity += 1;
                                        } else {
                                            // 如果不存在，添加新商品
                                            cartItems.push(cartItem);
                                        }
                                        
                                        // 保存到 localStorage
                                        localStorage.setItem('cart', JSON.stringify(cartItems));
                                        
                                        Toast.show('已添加到购物车');
                                        navigate('/app/cars');
                                    }}
                                >
                                    立即拼
                                </button>
                            </div>
                        </div>
                    </div>
                ))
                )}
            </div>
        </div>
    )
}
